#!/bin/bash

#set -x
set -e

# 环境
env=test
# 镜像仓库
harbor=172.20.45.68:81
# 命名空间 namespace
ns=yonbip
# kubeconfig 文件路径
kubeconfig=/root/.kube/config


function imagePullPolicy(){
  deploy=$1
  kubectl --kubeconfig ${kubeconfig}  patch deploy $deploy -n $ns --type='json' -p '[{"op": "replace", "path": "/spec/template/spec/containers/0/imagePullPolicy", "value":"Always"}]'
}

function restartDeploy(){
  deploy=$1
  kubectl --kubeconfig ${kubeconfig}  rollout restart -n $ns deploy/$deploy
}

function pullImage(){
  img=${1}
  docker images | grep ${img} && docker image rm ${img}
  docker pull ${img}
}

function dockerFile(){
  img=${1}
  cat > Dockerfile <<EOF
FROM ${img}
ADD app /app
EOF

  docker build -t ${img} .
  docker login -p Harbor12345 -u admin ${harbor}
  docker push ${img}
}

function getDeploy(){
  img=${1}
  tags=(${img//\// })
  tag=${tags[2]}

  names=(${tag//:/ })
  echo ${names[0]}
}


for item in `cat images.txt`;
do
  img=`echo ${item} | tr -d '\r'`
  pullImage ${img}
  dockerFile ${img}
  imgName=$(getDeploy ${img})

  deploy="${env}-${imgName}"
  imagePullPolicy $deploy
  restartDeploy $deploy
done
